import { createInjectionState } from '@vueuse/core';

import { useAgentChatStore } from '#/store/agentchat';

// 2. createInjectionState - 注入状态
export const [useProvideCounter, useInjectCounter] = createInjectionState(
  (initialValue: Ref) => {
    const agentChatStore = useAgentChatStore();

    // 获取聊天组件实例
    const bubbleListRef = ref(initialValue);

    // 处理第一条消息翻译事件导致滚动条被顶上去问题
    async function scrollToBottom(id: any) {
      if (
        id ===
        agentChatStore.conversationHistory[
          agentChatStore.conversationHistory.length - 1
        ]?.id
      ) {
        // 等待DOM更新后滚动到底部
        await nextTick();
        // 置于底部
        bubbleListRef.value?.scrollToBottom();
      }
    }

    return { bubbleListRef, scrollToBottom };
  },
);

// 提供一个带默认值的版本
export const useCounter = () => {
  const injectedState = useInjectCounter();
  // 如果没有提供状态，返回默认值
  if (!injectedState) {
    return {
      scrollToBottom: () => {},
      bubbleListRef: ref(),
    };
  }
  return injectedState;
};
